/**
 * @description: 单位管理的弹窗，同时支持新增、预览和编辑
 */
<template>
  <div class="addDialog" :class="{previewPage: isReadonly}">
    <el-dialog
      :close-on-click-modal="false"
      class="basic-from"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="1200px"
      @close="handleClosed"
    >
      <div class="dialogWrap">
        <el-form ref="dialogForm" :rules="rules" :model="formData" class="form-wrap">
          <h4 class="dialogItemTitle full">单位信息</h4>
          <el-form-item label="单位名称" prop="unitName">
            <el-input v-halfCharCode v-model="formData.unitName" maxlength="20" :readonly="isReadonly" placeholder="请输入单位名称" />
          </el-form-item>
          <el-form-item label="单位类型" prop="unitType">
            <el-select clearable v-model="formData.unitType" :disabled="isReadonly" placeholder="请选择单位类型">
              <el-option v-for="item in unitTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="社会统一信用代码" prop="creditCode">
            <el-input v-halfCharCode v-model="formData.creditCode" maxlength="18" :readonly="isReadonly" placeholder="请输入社会统一信用代码" />
          </el-form-item>
          <el-form-item label="联系人" prop="contactUser">
            <el-input v-halfCharCode v-model="formData.contactUser" maxlength="20" :readonly="isReadonly" placeholder="请输入联系人" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactTell">
            <el-input v-halfCharCode v-model="formData.contactTell" maxlength="20" :readonly="isReadonly" placeholder="请输入手机或座机号码" />
          </el-form-item>
          <el-form-item label="联系人手机" prop="contactPhone">
            <el-input v-halfCharCode v-model="formData.contactPhone" maxlength="20" :readonly="isReadonly" placeholder="请输入联系人手机" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-halfCharCode v-model="formData.address" maxlength="99" :readonly="isReadonly" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="业务范围" class="full" prop="problemDesc">
            <el-input v-halfCharCode v-model="formData.businessScope" type="textarea" :readonly="isReadonly" placeholder="请输入内容" maxlength="200" />
          </el-form-item>
          <el-form-item label="备注" class="full" prop="remarks">
            <el-input
              v-halfCharCode
              v-model="formData.remarks"
              type="textarea"
              :readonly="isReadonly"
              :placeholder="isReadonly ? '暂无内容' : '请输入内容'"
              maxlength="200"
            />
          </el-form-item>
          <!-- 附件 -->
          <div :span="24" v-if="oldFiles.length || type !== 'preview'">
            <h4 class="dialogItemTitle full">上传附件</h4>
          </div>
          <v-upload
            ref="upload"
            class="full"
            :busId="formData.paymentContractUnitId"
            modelType="paymentDepartment"
            @onSuccess="onSuccess"
            @loadCompleted="handleLoadCompleted"
            v-model="uploadFileList"
            :isView="['preview'].includes(type)"
            :canDelete="['add','edit'].includes(type)"
          />
        </el-form>
      </div>
      <div slot="footer">
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]">提 交</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editDepartment, checkCreditCode, checkUnitName } from "@/views/wy-operate/api/payment";
import { getDict } from '@/utils'
import { validateSocialCredit, validatePhoneTwo } from '@/utils/validate'
export default {
  name: "addDepartment",
  inject: ['initList'],
  data () {
    return {
      //弹窗类型，默认新增
      type: "add",
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        // 地址
        address: "",
        //业务范围
        businessScope: "",
        // 联系人手机号码
        contactPhone: "",
        // 	联系电话
        contactTell: "",
        // 联系人
        contactUser: "",
        // 社会统一信用码
        creditCode: "",
        // 主键id
        paymentContractUnitId: "",
        // 备注
        remarks: "",
        // 	单位名称
        unitName: "",
        // 单位类型
        unitType: ""
      },
      // 上传文件列表
      uploadFileList: [],
      // 已上传的文件
      oldFiles: [],
      // 校验
      rules: {
        unitName: [
          { required: true, message: "单位名称不能为空", trigger: "blur" },
          { validator: this.handleUnitNameRepeat, trigger: 'blur' },
        ],
        unitType: [{ required: true, message: "单位类型不能为空", trigger: "blur" }],
        creditCode: [
          { required: true, message: "社会统一信用代码不能为空", trigger: "blur" },
          { validator: validateSocialCredit, trigger: 'blur' },
          { validator: this.handleCreditCodeRepeat, trigger: 'blur' },
        ],
        contactUser: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
        contactTell: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { validator: validatePhoneTwo, trigger: 'blur' },
        ],
        contactPhone: [
          { required: true, message: "联系人手机不能为空", trigger: "blur" },
          { validator: validatePhoneTwo, trigger: 'blur' }
        ],
        address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
      },
    };
  },
  computed: {
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增"
      }[this.type];
    },
    // 判断是否只读
    isReadonly () {
      return ["preview"].includes(this.type);
    },
    // 单位类型
    unitTypes () {
      return getDict('payment-contract-unit-type')
    }
  },
  methods: {
    //开启弹窗
    show ({ type, data = {} }) {
      if (['preview', 'edit'].includes(type)) {
        this.formData = { ...this.formData, ...data };
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 提交新增
    async save () {
      if (['edit', 'add'].includes(this.type)) {
        const validate = await this.$refs.dialogForm.validate()
        validate && this.$refs.upload.submit();
      }
    },
    // 上传成功
    async onSuccess (response, file, fileList) {
      let params = this.type == 'add' ? { ...this.formData, paymentContractUnitId: response.data } : this.formData
      const res = await editDepartment(params, this.type)
      if (res.data.code == 0) {
        this.$message.success(`${this.dialogTitle}成功!`);
        this.initList({ keyword: '', current: 1 })
        this.dialogVisible = false;
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 选择物业名称
    chooseProperty () {
      this.$refs.propertyChoose.show("question");
    },
    // 弹窗关闭还原
    handleClosed () {
      this.uploadFileList = []
      this.oldFiles = []
      this.formData = {
        address: "",
        businessScope: "",
        contactPhone: "",
        contactTell: "",
        contactUser: "",
        creditCode: "",
        paymentContractUnitId: "",
        remarks: "",
        unitName: "",
        unitType: ""
      }
      this.$refs.dialogForm.resetFields();
    },
    // 监听上传组件上传完成
    handleLoadCompleted (data) {
      this.oldFiles = data
    },
    // 检查单位名称是否重复
    handleUnitNameRepeat (rule, value, callback) {
      let params = { unitName: value }
      if (this.type === 'edit') {
        params.paymentContractUnitId = this.formData.paymentContractUnitId
      }
      checkUnitName(params, this.type).then(res => {
        if (res.data.code == 0 && res.data.data) {
          return callback()
        }
        return callback(new Error('单位名称不能重复'))
      })
    },
    // 监听社会信用码重复
    handleCreditCodeRepeat (rule, value, callback) {
      let params = { creditCode: value }
      if (this.type === 'edit') {
        params.paymentContractUnitId = this.formData.paymentContractUnitId
      }
      checkCreditCode(params, this.type).then(res => {
        if (res.data.code == 0 && res.data.data) {
          return callback()
        }
        return callback(new Error('社会信用代码不能重复'))
      })
    }
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-dialog__body {
    padding: 16px 32px;
  }
}
</style>
